<template>
    <div class="main">
        <Header class="main_header"/>
        <div style="height: 63px;"></div>
        <div class="main_body">
            <h1 v-if="articleVo.id==0"><strong>发布文章</strong></h1>
            <h1 v-else><strong>修改文章</strong></h1>
            <a-textarea
                    class="main_body_title"
                    v-model:value="articleVo.title"
                    placeholder="请输入文章标题（5～100个字）"
                    :auto-size="{ minRows: 2, maxRows: 3 }"
                    allowClear
                    showCount
            />
            <ArticleEditor @sendContentToArticle="receiveChildContent" @keyup="deleteSurplusImg"
                           class="main_body_editor"/>
            <div class="main_body_label">
                <div class="main_body_label_name">文章标签:</div>
                <a-cascader
                        v-model:value="articleVo.label"
                        style="width: 50%"
                        multiple
                        :fieldNames="{ label: 'tagName', value: 'id', children: 'twoSorts', isLeaf: false }"
                        max-tag-count="responsive"
                        :options="oneAndTwoSortList"
                        showSearch
                        placeholder="添加文章标签(最多选择5个标签)"
                ></a-cascader>
            </div>
            <div class="main_body_type">
                <div class="main_body_label_name">发布形式:</div>
                <a-radio-group v-model:value="articleVo.type">
                    <a-radio class="main_body_type_radio" :value="1">全部可见</a-radio>
                    <a-radio class="main_body_type_radio" :value="2">仅我可见</a-radio>
                    <a-radio class="main_body_type_radio" :value="3">粉丝可见</a-radio>
                </a-radio-group>
            </div>
            <div class="main_body_keyword">
                <div class="main_body_label_name">关键词提取:</div>
                <a-input v-model:value="articleVo.keyword" class="main_body_keyword_text"/>
                <a-button @click="articleExtractText" type="primary" ghost>一键提取</a-button>
            </div>
            <div class="main_body_grade">
                <div class="main_body_label_name">内容等级:</div>
                <a-radio-group v-model:value="articleVo.grade">
                    <a-radio class="main_body_grade_radio" :value="1">初级</a-radio>
                    <a-radio class="main_body_grade_radio" :value="2">中级</a-radio>
                    <a-radio class="main_body_grade_radio" :value="3">高级</a-radio>
                </a-radio-group>
            </div>
            <div class="main_body_operation">
                <a-button v-if="articleVo.id==0" @click="handleSaveArticle" class="main_body_operation_publish">
                    发布文章
                </a-button>
                <a-button v-else @click="handleModifyArticle" class="main_body_operation_publish">修改文章</a-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import Header from '@/components/header/index.vue'
import ArticleEditor from '@/components/myRichText/articleEditor/index.vue'
import {onMounted, ref} from "vue"
import {ArticleVo} from "@/model/home/article";
import {getArticleDetails, getOneAndTwoSortList, modifyArticle, saveArticle} from "@/api/home/article";
// @ts-ignore
import Publish from 'pubsub-js'
// @ts-ignore
import cookie from 'js-cookie'
import {deleteImg} from "@/api/home/answer";
import {getText, isNull} from "@/utils/checkoutEditor";
import {message} from "ant-design-vue";
import {useRoute, useRouter} from "vue-router";
import {extractText} from "@/api/ai";
import {delHtmlTag} from "@/utils/htmlUtils";

const router = useRouter()

//提取文章关键词需要的参数
const articleKey = ref({
    content: ''
})

//文章内容提取
const articleExtractText = () => {
    if (articleVo.value.content != null) {
        articleKey.value.content = delHtmlTag(articleVo.value.content)
        extractText(articleKey.value).then((res) => {
            //提取到的内容列表
            articleVo.value.keyword = res.data.data.list
        })
    }
}

//一级和二级标签数组
const oneAndTwoSortList = ref()

//获取一级和二级标签
const handleOneAndTwoSortList = () => {
    getOneAndTwoSortList().then((res) => {
        oneAndTwoSortList.value = res.data.data.list
    })
}

//编辑文章
const handleArticleDetails = () => {
    const route = useRoute()
    if (route.query.articleId != null) {
        //获取路由参数
        const articleId: any = route.query.articleId
        getArticleDetails(articleId).then((res) => {
            articleVo.value = res.data.data.article
            //TODO 标签无法回显
            articleVo.value.label = ''
            Publish.publish('editArticle', articleVo.value.content)
        })
    }
}

//修改文章
const handleModifyArticle = () => {
    //校验消息是否为空
    let checkContent = getText(articleVo.value.content)
    if (articleVo.value.userId === 0) {
        message.error('网络异常，请稍后重试！')
    } else if (articleVo.value.title === '') {
        message.warn('标题不能为空！')
    } else if (articleVo.value.title.length <= 5 || articleVo.value.title.length >= 100) {
        message.warn('文章标题长度为5～100个字')
    } else if (isNull(checkContent)) {
        message.warn('内容不能为空！')
    } else if (articleVo.value.label.length === 0) {
        message.warn('标签不能为空！')
    } else if (articleVo.value.label.length >= 5) {
        message.warn('最多选择5个标签！')
    } else {
        modifyArticle(articleVo.value).then((res) => {
            message.success(res.data.message)
            router.push("/articleDetails?articleId=" + articleVo.value.id)
        })
    }
}

//写文章需要的参数
const articleVo = ref<ArticleVo>({
    id: 0,
    userId: 0,
    title: '',
    content: '',
    label: '',
    grade: 1,
    type: 1,
    keyword: ''
})

//发布文章
const handleSaveArticle = () => {
    //校验消息是否为空
    let checkContent = getText(articleVo.value.content)
    if (articleVo.value.userId === 0) {
        message.error('网络异常，请稍后重试！')
    } else if (articleVo.value.title === '') {
        message.warn('标题不能为空！')
    } else if (articleVo.value.title.length <= 5 || articleVo.value.title.length >= 100) {
        message.warn('文章标题长度为5～100个字')
    } else if (isNull(checkContent)) {
        message.warn('内容不能为空！')
    } else if (articleVo.value.label.length === 0) {
        message.warn('标签不能为空！')
    } else if (articleVo.value.label.length >= 5) {
        message.warn('最多选择5个标签！')
    } else {
        saveArticle(articleVo.value).then(() => {
            //清除富文本编辑器内容
            Publish.publish('clearContentToArticle')
            articleVo.value.content = '<p></p>'
            message.success("发布成功")
            router.push("/")
        })
    }
}

//删除的图片名数组,防止垃圾图片残留
const imgDelName = ref<any>([])

//接收子组件传过来的值
const receiveChildContent = (arr: string) => {
    articleVo.value.content = arr[0]
    imgDelName.value = arr[1]
}

//按删除键时并且多余的图片不为0时执行
const deleteSurplusImg = (e: any) => {
    if (e.keyCode === 8 && imgDelName.value.length != 0) {
        //删除多余图片
        deleteImg(imgDelName.value).then(() => {
        })
    }
}

//从cookie中获取用户id
const getUserId = () => {
    if (cookie.get('userinfo') != null) {
        articleVo.value.userId = JSON.parse(cookie.get('userinfo')).id
    } else {
        articleVo.value.userId = 0
    }
}

getUserId()
onMounted(() => {
    handleOneAndTwoSortList()
    handleArticleDetails()
})
</script>

<style lang="less" scoped>
.main {
  height: 100%;
  width: 100%;

  .main_header {
    height: 70px;
    position: fixed;
    width: 100%;
    z-index: 99999;
  }

  .main_body {
    margin-left: 20%;
    margin-right: 20%;
    margin-top: 20px;
    background-color: #ffffff;
    padding: 10px;

    .main_body_title {
      margin-top: 10px;
      height: 50px;
      min-height: 32px;
    }

    ::placeholder {
      font-size: 20px;
      line-height: 20px;
    }

    .main_body_editor {
      width: 100%;
    }

    .main_body_label {
      display: flex;
      margin-top: 30px;

      .main_body_label_name {
        margin-right: 20px;
        line-height: 30px;
      }
    }

    .main_body_type {
      display: flex;
      margin-top: 30px;

      .main_body_label_name {
        margin-right: 20px;
      }

      .main_body_type_radio {
        margin-right: 30px;
      }
    }

    .main_body_keyword {
      display: flex;
      margin-top: 30px;

      .main_body_label_name {
        margin-right: 20px;
      }

      .main_body_keyword_text {
        width: 485px;
      }
    }

    .main_body_grade {
      display: flex;
      margin-top: 30px;

      .main_body_label_name {
        margin-right: 20px;
      }

      .main_body_grade_radio {
        margin-right: 30px;
      }
    }

    .main_body_operation {
      float: right;
      padding-bottom: 20px;
      padding-top: 10px;

      .main_body_operation_publish {
        margin: 5px;
        height: 40px;
        padding: 8px 16px;
        font-size: 16px;
        color: #fff;
        border: none;
        white-space: nowrap;
        background: #fc5531;
        border-radius: 100px;
      }
    }
  }
}
</style>